package com.linzm.leetcode.mid.tree.翻转二叉树;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @Author zimingl
 * @Date 2023/2/21 22:13
 * @Description: TODO
 */
public class InvertTree226 {
    public static void main(String[] args) {
        InvertTree226 invertTree226 = new InvertTree226();
        TreeNode treeNode = invertTree226.stackPreInvertTree(TreeNode.getTree());
        System.out.println(treeNode);
    }

    /**
     * DFS递归
     * 前后序遍历都可以
     * 中序不行，因为先左孩子交换孩子，再根交换孩子（做完后，右孩子已经变成了原来的左孩子），再右孩子交换孩子（此时其实是对原来的左孩子做交换）
     */
    public TreeNode dfsPostInvertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        dfsPostInvertTree(root.left);
        dfsPostInvertTree(root.right);
        swapChildren(root);
        return root;
    }

    public TreeNode dfsPreInvertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        swapChildren(root);
        dfsPreInvertTree(root.left);
        dfsPreInvertTree(root.right);
        return root;
    }

    public TreeNode dfsInInvertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        dfsPreInvertTree(root.left);
        swapChildren(root);
        dfsPreInvertTree(root.left);
        return root;
    }

    private void swapChildren(TreeNode root) {
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
    }

    // dfs 栈
    // 为什么这个中序就是可以的呢，因为这是用栈来遍历，而不是靠指针来遍历，避免了递归法中翻转了两次的情况，大家可以画图理解一下，这里有点意思的。
    // 常规的中序 左中右可以 非常规遍历 右中左也可以
    public TreeNode stackPreInvertTree(TreeNode root) {
        if (root == null) return root;
        Deque<TreeNode> stack = new LinkedList<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            if (node != null) {
                if (node.right != null) stack.push(node.right);
                stack.push(node);
                stack.push(null);
                if (node.left != null) stack.push(node.left);
            } else {
                node = stack.pop();
                swapChildren(node);
            }
        }
        return root;
    }

    // bfs 队列
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        Deque<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size-- > 0) {
                TreeNode node = queue.poll();
                swapChildren(node);
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
        }
        return root;
    }
}

